package utils

import (
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt"
	"time"
)

type CustomClaims struct {
	UserId int32
	RoleId int32
	jwt.StandardClaims
}


const (
	secret = "123456"
)

func GetToken(user_id int32, role_id int32, expire int64) (string, error) {
	claims := CustomClaims{
		user_id,
		role_id,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Unix()+expire,
			Issuer:    "admin",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenStr, err := token.SignedString([]byte(secret))
	return tokenStr, err
}

func VerityToken(token string) error{
	tokens, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secret), nil
	})

	if claims, ok := tokens.Claims.(jwt.MapClaims); ok && tokens.Valid {
		if int(claims["UserId"].(float64)) <= 0 {
			return errors.New("auth token: data is 0")
		}
		return nil
	} else {
		fmt.Println("auth token:", err)
		return err
	}
}

func GetJwtData(token string) (int32, int32, error){
	tokens, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secret), nil
	})
	if claims, ok := tokens.Claims.(jwt.MapClaims); ok{
		return int32(claims["UserId"].(float64)), int32(claims["RoleId"].(float64)),nil
	}

	return 0, 0, err
}
